<template>
    <div class='login'>
        <el-card header="登录信息" class="login-card">
            <el-form :model="model" :rules="rules" ref="ruleForm" label-width="70px" @submit.native.prevent="login">
                <el-form-item prop="username" label="用户名">
                    <el-input v-model="model.username"></el-input>
                </el-form-item>
                <el-form-item prop="password" label="密码">
                    <el-input type="password" v-model="model.password"></el-input>
                </el-form-item>
                <el-form-item label-width="0px" style="textAlign: center">
                    <el-button type="primary" native-type="submit">登录</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
<script>
export default {
    data() {
        return {
            model: {
                username: '',
                password: ''
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ]
            }
        }
    },
    methods: {
        login() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.$http.post('login',this.model).then(res => {
                        if (res.status === 200) {
                            this.$store.commit('setToken',res.data.token)
                            this.$store.commit('setUsername',res.data.username)
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            })
                            this.$router.push({
                                name: 'Home'
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: res.data.msg
                            })
                        }
                    }).catch(err => {
                        this.$message({
                            type: 'error',
                            message: err.response.data.msg
                        })
                    })
                }else {
                    return false
                }
            })
        }
    },
}
</script>
<style lang='scss'>
.login {
    width: 100%;
    height: 100vh;
    background: url(https://src.mcool.com/data/attachment/forum/201907/04/003617b463f0mglp8u46up.jpg-1440) 100% 100%/100% 100%;
}
.login-card {
    width: 400px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
}
</style>